import sys
import os

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.FCDB import FCDB
from src.db.LocalDb import LocalDb
from src.utils.CommonUtils import cleanScreen
from src.utils.LogUtils import Logger


class SyncTqBdDflt:
    def __init__(self, logger: Logger, localDb: LocalDb, fcdb: FCDB):
        self.logger = logger
        self.localDb = localDb
        self.fcdb = fcdb
        self.size = 1000

    def __queryMaxTmStamp__(self, tableName):
        sql = f"""
            select max(TMSTAMP) as maxTMSTAMP from {tableName}
        """
        r = self.localDb.QueryOne(sql)
        if r is None or r["maxTMSTAMP"] is None:
            return 0
        return r["maxTMSTAMP"]

    def __queryFcdbData__(self, maxTmStamp, columns, tableName, size):
        queryColumns = ",".join(columns)
        sql = f"""
         SELECT {queryColumns} FROM {tableName} where TMSTAMP > %s order by TMSTAMP asc limit %s
        """
        return self.fcdb.Query(sql, (maxTmStamp, size))

    def __updateLocal__(self, tableName, columns, updateDatas):
        updateColumns = ",".join(columns)
        updateValues = ",".join(f"%({c})s" for c in columns)
        sql = f"""    
            REPLACE INTO {tableName}
            ({updateColumns})
            VALUES
            ({updateValues});
        """
        return self.localDb.ExecMany(sql, updateDatas)

    def __sync__(self, tableName, columns):
        self.logger.info(f"同步 {tableName}")
        total = 0
        while True:
            maxTmStamp = self.__queryMaxTmStamp__(tableName=tableName)
            self.logger.info(f"当前 {tableName}.maxTMSTAMP {maxTmStamp}")
            updateDatas = self.__queryFcdbData__(maxTmStamp=maxTmStamp, columns=columns, tableName=tableName, size=self.size)
            self.__updateLocal__(tableName=tableName, columns=columns, updateDatas=updateDatas)
            total += len(updateDatas)
            self.logger.info(f"更新 {tableName} {len(updateDatas)}，合计更新 {total}")
            if len(updateDatas) < self.size:
                break

    def sync(self):
        tableName = "tq_bd_dfltinfo"
        columns = ["ID", "DEFLTINFOID", "PUBLISHDATE", "UPDATEDATE", "SECURITYID",
                   "SNAME", "PFPAYDATE", "CASHFTYPE", "ISBDDFLT", "BDAMT",
                   "NEWDEFLTTYPE", "NEWPAYDATE", "NEWLINEINFO", "NEWFOLLOW", "FSECODE",
                   "COMPCODE", "BDSPE", "BCODE", "MEMO", "ISVALID",
                   "TMSTAMP", "ENTRYDATE", "ENTRYTIME", "DATA_DOWNLOAD_TIME"]
        self.__sync__(tableName=tableName, columns=columns)

        tableName = "tq_bd_dfltlist"
        columns = ["ID", "DFLTLISTID", "PUBLISHDATE", "UPDATEDATE", "DATASOURCE",
                   "SECURITYID", "SENAME", "COMPCODE", "COMPNAME", "PFPAYDATE",
                   "PFPAYDATEPP", "CASHFTYPE", "DFLTRES", "BDDEBTAMT", "PFPAMT",
                   "PFIAMT", "PFTOTAMT", "ACTPAYPAMT", "ACTPAYIAMT", "ACTPAYTOTAMT",
                   "DFLTPAMT", "DFLTIAMT", "DFLTTOTAMT", "DFLTEXP", "DFLTINFOID",
                   "ISVALID", "TMSTAMP", "ENTRYDATE", "ENTRYTIME", "DATA_DOWNLOAD_TIME"]
        self.__sync__(tableName=tableName, columns=columns)

        tableName = "tq_bd_dfltsolvelist"
        columns = ["ID", "DFLTSOLVELISTID", "PUBLISHDATE", "UPDATEDATE", "DATASOURCE",
                   "SECURITYID", "SENAME", "COMPCODE", "COMPNAME", "PFPAYDATE",
                   "PFPAYDATEPP", "CASHFTYPE", "SOLVENUM", "SOLVEDATE", "SOLVEMODE",
                   "CAPSOURCE", "SOLVEPAMT", "SOLVEIAMT", "SOLVETAMT", "SOLVEFAMT",
                   "EXTRAAMT", "TOTSOLVEPAMT", "TOTSOLVEIAMT", "TOTSOLVETAMT", "TOTSOLVEFAMT",
                   "SDFLTPAMT", "SDFLTIAMT", "SDFLTTOTAMT", "SOLVESTATUS", "ISNEWEST",
                   "DFLTLISTID", "DFLTINFOID", "SOLVEEXP", "ISVALID", "TMSTAMP",
                   "ENTRYDATE", "ENTRYTIME", "DATA_DOWNLOAD_TIME", "DISPMODE"]

        self.__sync__(tableName=tableName, columns=columns)

        tableName = "tq_bd_dflttline"
        columns = ["ID", "TIMELINKID", "SECURITYID", "DATASOURCE", "RELEID",
                   "PUBLISHTIME", "TITLE", "SHOWRANK", "SHOWDATE", "SHOWTITLE",
                   "ISTIMELINE", "ISIMP", "COMPCODE", "COMPMAINID", "BDSPE",
                   "BCODE", "ISVALID", "TMSTAMP", "ENTRYDATE", "ENTRYTIME",
                   "DATA_DOWNLOAD_TIME"]

        self.__sync__(tableName=tableName, columns=columns)

        tableName = "tq_bd_newestbasicinfo"
        columns = ["ID", "SECURITYID", "SECODE", "BONDNAME", "BONDSNAME", "SYMBOL", "EXCHANGE", "TMSTAMP"]
        self.__sync__(tableName=tableName, columns=columns)

        tableName = "tq_bd_otcbasicinfo"
        columns = ["ID", "SECURITYID", "SECODE", "BONDNAME", "BONDSNAME", "SYMBOL", "EXCHANGE", "TMSTAMP"]
        self.__sync__(tableName=tableName, columns=columns)


def main():
    logger = Logger()
    cleanScreen()
    logger.info("============同步债券违约数据 开始================")

    localDb = LocalDb(logSql=False, autocommit=True)
    fcdb = FCDB(logSql=False, autocommit=True)

    sync = SyncTqBdDflt(logger=logger, localDb=localDb, fcdb=fcdb)
    sync.sync()
    logger.info("============同步债券违约数据 结束================")


# 程序入口
if __name__ == "__main__":
    main()
